import Vue from 'vue'
import Router from 'vue-router'
import axios from 'axios'
import md5 from 'js-md5';
// import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import {
	Modal,
	notification
} from 'ant-design-vue'
import router from '@/router'
import store from '@/store'
import {
	VueAxios
} from './axios'
let whiteList = ['product/attributePull'];
axios.defaults.withCredentials = false;
// 创建 axios 实例
// 
const service = axios.create({
	baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
	timeout: 6000 * 3 // 请求超时时间
})

// axios.defaults.transformRequest = [data => qs.stringify(data)];
let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
let cancelToken = axios.CancelToken; //取消接口请求
let removePending = (config) => {
	for (let p in pending) {
		if (pending[p].u === config.url + '&' + config.method) { //当当前请求在数组中存在时执行函数体
			pending[p].f(); //执行取消操作
			pending.splice(p, 1); //把这条记录从数组中移除
		}
	}
}
const err = (error) => {
	console.log(error)
	if (error.message && error.message.includes('timeout')) { // 判断请求异常信息中是否含有超时timeout字符串
		message.error('请求超时了');
	}
	if (error.response) {
		console.log(error.response.data)
		message.error(error.response.data.msg ? error.response.data.msg : '发生错误了！');

	}
	return Promise.reject(error)
};
// request 拦截器
service.interceptors.request.use(config => {
		if (!config.url) {
			return false
		}
		let token = window.localStorage.getItem("token");
		if (token && config.url && config.url.indexOf("/login") == -1) {
			/* 判断url地址上面已经*/
			config.headers['Authorization'] = token;
		}
		// if (config.url.indexOf("/common/uploadFile") == -1) {
		// 	if (config.data) {
		// 		let md4data = md5(JSON.stringify(config.data))
		// 		config.headers['X-AUTH-SIGN'] = md4data
		// 	}
		// 	config.headers['X-AUTH-TIME'] = new Date().getTime();
		// }
		return config
	},
	err)

// response 拦截器
service.interceptors.response.use((response) => {
	removePending(response.config); //在一个ajax响应后再执行一下取消操作，把已经完成的请求从pending中移除
	if (response.data.code != 200) {
		if (response.data.code == 512) {
			store.dispatch('Logout').then(() => {
				window.location.reload()
			})
		} else {
			message.error(response.data.message ? response.data.message :
				'发生错误了！');
		}
	}
	return response.data;


}, err)

const installer = {
	vm: {},
	install(Vue) {
		Vue.use(VueAxios, service)
	}
}

export {
	installer as VueAxios,
	service as axios
}
